/**
 * 
 */
package org.mhz.ootw.service;

import java.io.StringWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringUtils;
import org.mhz.ootw.annotation.LogTimeTaken;
import org.mhz.ootw.dataaccess.MenuDAO;
import org.mhz.ootw.entity.MenuItem;
import org.mhz.ootw.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.googlecode.ehcache.annotations.Cacheable;

/**
 * @author Mahan
 * 
 * XML menu service
 */
@Service(Constants.XML_MENU_SERVICE)
public class XMLMenuService implements MenuService
{
    private static final Logger LOGGER = LoggerFactory.getLogger(XMLMenuService.class);

    @Resource(name = Constants.MENU_DAO)
    private MenuDAO mMenuDAO;

    /*
     * (non-Javadoc)
     * 
     * @see org.mhz.ootw.service.MenuService#getMenu()
     */
    @Override
    @LogTimeTaken
    @Cacheable(cacheName = Constants.OCEAN_CACHE)    
    public String getMenu()
    {
        final List<MenuItem> menuItems = mMenuDAO.getAll();        
        final String menu = createXML(menuItems);

        LOGGER.trace(menu);
        
        return menu;
    }

    /**
     * @param aMenuItems - The menu items
     * @return The menu as an xml document
     */
    private String createXML(final List<MenuItem> aMenuItems)
    {
    	String xmlResult = "No XML returned";
    	
        try
        {
            final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // root elements
            final Document doc = docBuilder.newDocument();
            final Element rootElement = doc.createElement("root");
            doc.appendChild(rootElement);

            String nodeId = "";
            String nodeName = "";
            String nodeType = "";
            String nodeParentId = "";
            //String nodeContentLocation = "";
            
            for (MenuItem menuItem : aMenuItems)
            {            
                nodeId = menuItem.getNodeId();            
                nodeName = menuItem.getNodeName();
                nodeType = menuItem.getNodeType();
                nodeParentId = menuItem.getNodeParentId();
                //nodeContentLocation = menuItem.getNodeContentLocation();
                
                // item elements
                final Element item = doc.createElement("item");
                rootElement.appendChild(item);
    
                // set id attribute to the item element                
                item.setAttribute("id", nodeId);
                
                // set parent_id attribute to the item element
                if (StringUtils.isBlank(nodeParentId))
                {
                	nodeParentId = "0";
                }
                item.setAttribute("parent_id", nodeParentId); 
                
                // Add the rel attribute if type exists
                if (StringUtils.isNotBlank(nodeType))
                {  
	                item.setAttribute("rel", nodeType); 
                }
                
                // Add the location attribute if location exists
                /*if (StringUtils.isNotBlank(nodeContentLocation))
                {  
                    item.setAttribute("location", nodeContentLocation); 
                } */               
    
                // content element
                final Element content = doc.createElement("content");
                item.appendChild(content);
    
                // lastname elements
                final Element name = doc.createElement("name");
                name.appendChild(doc.createTextNode(nodeName));
                content.appendChild(name);
            }

            // convert the xml to a string
            final Source source = new DOMSource(doc);
            final StringWriter stringWriter = new StringWriter();
            final Result result = new StreamResult(stringWriter);
            
            final TransformerFactory factory = TransformerFactory.newInstance();
            final Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty("encoding", "ISO-8859-1");
            transformer.transform(source, result);
            
            xmlResult = stringWriter.getBuffer().toString();
            
            // Replace double quotes with single quotes
            xmlResult = xmlResult.replaceAll("\"", "\'");
        }
        catch (ParserConfigurationException pceEx)
        {
        	pceEx.printStackTrace();
        }
        catch (TransformerException tfeEx)
        {
        	tfeEx.printStackTrace();
        }
        
        return xmlResult;
    }
}
